// dui-demo.cpp : main source file
//

#include "stdafx.h"
#include "Application.h"
#include "Helper.h"
#ifdef _DEBUG
#include <vld.h>
#endif // _DEBUG

//定义唯一的一个R,UIRES对象,ROBJ_IN_CPP是resource.h中定义的宏。
ROBJ_IN_CPP

HANDLE g_hSemaphore = nullptr;

int WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPTSTR lpstrCmdLine, int /*nCmdShow*/)
{
  HRESULT hRes = OleInitialize(NULL);
  SASSERT(SUCCEEDED(hRes));

  int nRet = 0;

  std::vector<std::wstring> vecCmd;
  bool bCmd = CHelper::ParseCommandLine(vecCmd);
  if (bCmd)
    return nRet;

  g_hSemaphore = ::CreateSemaphore(NULL, 1, 1, SINGLEINSTANCENAME);
  // 信号量存在，则程序已有一个实例运行
  if (GetLastError() == ERROR_ALREADY_EXISTS) {
    printf("ERROR_ALREADY_EXISTS");
    Sleep(100);
    // 关闭信号量句柄
    // 寻找先前实例的主窗口
    int nCount = 10;
    while (nCount-- >= 0)//给2次机会
    {
      HWND hWndPrevious = ::GetWindow(::GetDesktopWindow(), GW_CHILD);
      while (::IsWindow(hWndPrevious))
      {
        // 检查窗口是否有预设的标记?  有，则是我们寻找的主窗
        if (::GetProp(hWndPrevious, SINGLEINSTANCENAME))
        {
          if (vecCmd.size() > 1)
          {
            CHelper::SendCommandLine(hWndPrevious, vecCmd);
          }
          ::ShowWindow(hWndPrevious, SW_SHOWNORMAL);
          // 退出本实例
          OleUninitialize();
          return FALSE;
        }
        // 继续寻找下一个窗口
        hWndPrevious = ::GetWindow(hWndPrevious, GW_HWNDNEXT);
      }
      // 前一实例已存在，但找不到其主窗
      // 可能出错了,也有可能窗口还未初始化成功
      Sleep(100);
    }
    OleUninitialize();
    return FALSE;
  }

  Application::Instance()->Initialize(hInstance);
  nRet = Application::Instance()->Run();
  Application::Instance()->UnInitialize();

  OleUninitialize();
  return nRet;
}
